import { Material, Object3D, Texture } from 'three'

/**
 * 参照文档 https://threejs.org/manual/#zh/cleanup
 * 用于销毁threejs创建的对象
 *
 * 使用方式 先引用该文件，然后在需要销毁的地方调用destroy方法
 *  this.resMgr = new ResourceTracker()
 *  this.track = this.resMgr.track.bind(this.resMgr)
 *  this.track(需要使用new的地方调用)
 *  比如 const m = this.track(new MeshBasicMaterial())
 */

export default class ResourceTracker {
  private resources

  constructor() {
    this.resources = new Set()
  }
  track(resource) {
    if (!resource) {
      return resource
    }

    // handle children and when material is an array of materials or
    // uniform is array of textures
    if (Array.isArray(resource)) {
      resource.forEach((resource) => this.track(resource))
      return resource
    }

    if (resource.dispose || resource instanceof Object3D) {
      this.resources.add(resource)
    }

    if (resource instanceof Object3D) {
      this.track(resource.geometry)
      this.track(resource.material)
      this.track(resource.children)
    } else if (resource instanceof Material) {
      // We have to check if there are any textures on the material
      for (const value of Object.values(resource)) {
        if (value instanceof Texture) {
          this.track(value)
        }
      }

      // We also have to check if any uniforms reference textures or arrays of textures
      if (resource.uniforms) {
        for (const value of Object.values(resource.uniforms)) {
          if (value) {
            const uniformValue = value.value
            if (uniformValue instanceof Texture || Array.isArray(uniformValue)) {
              this.track(uniformValue)
            }
          }
        }
      }
    }

    return resource
  }
  untrack(resource) {
    this.resources.delete(resource)
  }
  dispose() {
    console.log('销毁的数量:', this.resources.size)
    for (const resource of this.resources) {
      if (resource instanceof Object3D) {
        if (resource.parent) {
          resource.parent.remove(resource)
        }
      }

      if (resource.dispose) {
        resource.dispose()
      }
    }

    this.resources.clear()
  }
}

/*
// 使用方式
const resMgr = new ResourceTracker();
const track = resMgr.track.bind(resMgr);
track(gltf.scene);
// 需要删除的时候调用
resMgr.dispose();
*/
